﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NetFrameworkExtensions.Mathematics
{
  public class LinearRegressionAccumulator
  {
    int count;
    double sumX;
    double sumX2;
    double sumY;
    double sumXY;

    public int Count { get { return count; } }
    public double SumX { get { return sumX; } }
    public double SumX2 { get { return sumX2; } }
    public double SumY { get { return sumY; } }
    public double SumY2 { get { return sumXY; } }
    public double M
    {
      get
      {
        if (count <= 0) throw new InvalidOperationException("Not enough data");
        if (count == 1)
          return 0;
        if (sumX == 0)
          if (sumX2 == 0)
            throw new InvalidOperationException("Not enough data");
          else
            return sumXY / sumX2;
        double den = sumX * sumX - count * sumX2;
        if (den == 0) throw new InvalidOperationException("Not enough data");
        double num = sumX * sumY - count * sumXY;
        return num / den;
      }
    }
    public double N
    {
      get
      {
        if (count <= 0) throw new InvalidOperationException("Not enough data");
        if (count == 1)
          return sumY;
        if (sumX == 0)
          return sumY / count;
        return (sumXY - M * sumX2) / sumX;
      }
    }

    public void Add(double x, double y)
    {
      count++;
      sumX += x;
      sumX2 += x * x;
      sumY += y;
      sumXY += x * y;
    }

    public void Remove(double x, double y)
    {
      count--;
      sumX -= x;
      sumX2 -= x * x;
      sumY -= y;
      sumXY -= x * y;
    }
  }
}
